package com.gill.demo;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;

/**
 * curator修改znode的demo演示
 */
public class CuratorZnodeModify {

    public CuratorFramework client;
    public static final String zkServerPath = "env:2181";

    /**
     * 实例化zk客户端
     */
    public CuratorZnodeModify() {
        /**
         * curator连接zookeeper的策略:RetryNTimes（本次案例采用该连接策略）
         * n：重试的次数
         * sleepMsBetweenRetries：每次重试间隔的时间
         */
        RetryPolicy retryPolicy = new RetryNTimes(3, 5000);

        client = CuratorFrameworkFactory.builder()
                .connectString(zkServerPath)
                .sessionTimeoutMs(10000)
                .retryPolicy(retryPolicy)
                .namespace("workspace")
                .build();

        // 连接zk服务端
        client.start();

    }

    /**
     *
     * @Description: 关闭zk客户端连接
     */
    public void closeZKClient() {
        if (client != null) {
            this.client.close();
        }
    }

    public static void main(String[] args) throws Exception {
        // 连接zk服务端，创建zk客户端实例
        CuratorZnodeModify curator = new CuratorZnodeModify();
        boolean isZkCuratorStarted = curator.client.isStarted();
        System.out.println("当前客户的状态：" + (isZkCuratorStarted ? "连接中" : "已关闭"));

        // 修改节点数据（前提条件，在zk服务端创建/super/imooc节点，然后用curator客户端修改节点值）
        String nodePath = "/super/imooc";
		byte[] data = "modify-data1".getBytes();
//        curator.client.setData().withVersion(2).forPath(nodePath,data);
        curator.client.setData().forPath(nodePath,data);//经过测试，发现不写version也可以，应该是curator会自动获取znode的dataVersion

        // 关闭连接
        curator.closeZKClient();
        boolean isZkCuratorStarted2 = curator.client.isStarted();
        System.out.println("当前客户的状态：" + (isZkCuratorStarted2 ? "连接中" : "已关闭"));
    }

}
